/**
 * for login
 * ibio-develop
 */
(function(){
var m_data = {};
chrome.extension.sendMessage({type:"getData", key:KEY_HE_DATA}, init);

function init(result){
	var noticeIsNull = /^\s+$/.test($("#notice").text());
	m_data = result;
	trace("data", m_data);
	trace("notice is null:", noticeIsNull);
	//
	if(m_data.isWorking){
		if(m_data.username && m_data.password && noticeIsNull){
			login();
		}else{
			updateButtonUI();
		}
	}
}

function updateButtonUI(){
	var btn = $("#loginButton").clone();
	// trace("btn", btn);
	$("#loginButton").remove();
	btn.click(onLoginBtnClick);
	$("form").append(btn);
}

function login () {
	 $("#username").val(m_data.username);
	 $("#password").val(decrypt(m_data.password));
	 $("form:eq(0)").submit();
}

function onLoginBtnClick(e) {
	//save data
	m_data.username = $("#username").val();
	m_data.password = encrypt($("#password").val());
	chrome.extension.sendMessage({type:"setData", key:KEY_HE_DATA, value:m_data}, function(){
		trace("on login info saved!", m_data);
		login();
	});
}

//===============================
function encrypt(value){
	DES.init(ENCRYPTION_KEY, encodeURI(value));
	return DES.Encrypt();
}

function decrypt(value){
	DES.init(ENCRYPTION_KEY, value);
	return decodeURI(DES.Encrypt("Decrypt"));
}

}).call(this);